<template>
  <div class="app-container">
    <!-- 出库 -->

    <el-row :gutter="24">
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <!-- 搜索 -->
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="入库编号" prop="code">
              <el-input
                v-noSpace
                v-model="queryParams.code"
                placeholder="请输入入库编号"
                clearable
                class="!w-[192px]"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="来源类型" prop="sourceCategory">
              <el-select
                v-model="queryParams.sourceCategory"
                placeholder="请选择来源类型"
                filterable
                clearable
                class="!w-[192px]"
                @change="handleQuery"
              >
                <el-option
                  v-for="item in sourceCategoryList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="来源编号" prop="sourceCode">
              <el-select
                v-model="queryParams.sourceCode"
                placeholder="请选择来源编号"
                filterable
                class="!w-[192px]"
                clearable
                @change="handleQuery"
                remote
                :remote-method="(e: any) => getsourceCodeName(e, 'search')"
              >
                <el-option
                  v-for="item in sourceCodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择状态"
                class="!w-[192px]"
                filterable
                clearable
                @change="handleQuery"
              >
                <el-option
                  v-for="item in statusValueList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="入库日期" prop="timeScopes">
              <el-date-picker
                v-model="queryParams.timeScopes"
                type="daterange"
                placeholder="选择入库日期"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                picker-options="pickerOptions"
                clearable
                @change="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="search" @click.stop="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click.stop="handleResetQuery">重置</el-button>
              <el-button
                type="warning"
                v-hasPerm="'sys:stockIn:edit'"
                icon="menu"
                @click.stop="handleOpenDialog({}, 'add')"
              >
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 仓库列表 -->
        <el-card shadow="never">
          <el-table
            v-loading="loading"
            show-overflow-tooltip
            :tooltip-formatter="tableRowFormatter"
            height="300px"
            :data="pageData"
            @row-click="handClikRow"
          >
            <el-table-column prop="code" label="入库编号" />

            <el-table-column prop="sourceCategory" label="来源类型">
              <template #default="scope">
                <div>{{ sourceCategoryValue(scope.row.sourceCategory) }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <div>{{ statusValueFormat(scope.row.status) }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="sourceCode" label="来源编号" />
            <el-table-column prop="issueDate" label="入库日期" />
            <el-table-column prop="reason" label="入库类别">
              <template #default="scope">
                <el-tag v-if="scope.row.reason">
                  {{
                    reasonList?.filter((item: any) => item.value == scope.row.reason)?.[0]?.label ||
                    ""
                  }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
            <el-table-column label="操作" fixed="right" width="170" align="center">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status == '1'"
                  v-hasPerm="'sys:stockIn:app'"
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleOpenDialog(scope.row, 'app')"
                >
                  审核
                </el-button>
                <el-button
                  v-if="scope.row.status == '3'"
                  v-hasPerm="'sys:stockIn:app'"
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleOpenDialog(scope.row, 'appAgin')"
                >
                  再次审核
                </el-button>
                <el-button
                  v-if="scope.row.status < '4'"
                  v-hasPerm="'sys:stockIn:edit'"
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleOpenDialog(scope.row, 'edit')"
                >
                  修改
                </el-button>
                <el-button
                  v-if="scope.row.status < '4'"
                  v-hasPerm="'sys:stockIn:del'"
                  type="danger"
                  size="small"
                  link
                  @click.stop="handleOpenDialog(scope.row, 'del')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
      <!-- 二级列表 -->
      <el-col :lg="12" :xs="12" class="mt20">
        <el-card shadow="never">
          <el-button
            v-hasPerm="'sys:stockIn:product:edit'"
            type="warning"
            icon="menu"
            :disabled="rowIsshow"
            @click.stop="addRowDialog({}, 'add')"
          >
            新增
          </el-button>
          <el-table
            v-loading="loading"
            show-overflow-tooltip
            :tooltip-formatter="tableRowFormatter"
            height="250px"
            :data="rowData"
            @row-click="handClikBottom"
          >
            <el-table-column prop="code" label="编号" />
            <el-table-column
              :show-overflow-tooltip="false"
              prop="productCode"
              label="产品名称/编号"
              width="180"
            >
              <template #default="scope">
                <el-tooltip :content="productCodeFormat(scope.row.productCode)" placement="top">
                  <div class="ellipsisClass">{{ productCodeFormat(scope.row.productCode) }}</div>
                </el-tooltip>
              </template>
            </el-table-column>

            <el-table-column prop="qty" label="重量">
              <template #default="scope">
                <div>
                  {{ scope.row.qty }}
                  {{ unitFormat(scope.row.unit) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" />

            <el-table-column label="操作" fixed="right" width="100" align="center">
              <template v-if="!rowIsshow" #default="scope">
                <el-button
                  v-hasPerm="'sys:stockIn:product:edit'"
                  type="primary"
                  link
                  size="small"
                  @click.stop="addRowDialog(scope.row, 'edit')"
                >
                  修改
                </el-button>
                <el-button
                  v-if="rowList.status != '4'"
                  v-hasPerm="'sys:stockIn:product:del'"
                  type="danger"
                  size="small"
                  link
                  @click.stop="addRowDialog(scope.row, 'del')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="totalRow"
            v-model:page="rowParams.pageNum"
            v-model:limit="rowParams.pageSize"
            @pagination="handClikRow({ code: rowId, parentCode: rowId })"
          />
        </el-card>
      </el-col>
      <!-- 三级列表 -->
      <el-col :lg="12" :xs="12" class="mt20">
        <el-card shadow="never">
          <!-- <el-button
            v-hasPerm="'sys:stockIn:edit'"
            type="warning"
            icon="menu"
            :disabled="bottomIsshow"
            @click.stop="addBottomDialog({}, 'add')"
          >
            新增
          </el-button> -->
          <el-table
            v-loading="loading"
            show-overflow-tooltip
            :tooltip-formatter="tableRowFormatter"
            :data="bottomData"
          >
            <el-table-column prop="code" label="编号" />
            <el-table-column
              :show-overflow-tooltip="false"
              prop="productCode"
              label="产品名称/编号"
              width="180"
            >
              <template #default="scope">
                <el-tooltip :content="productCodeFormat(scope.row.productCode)" placement="top">
                  <div class="ellipsisClass">{{ productCodeFormat(scope.row.productCode) }}</div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="basket" label="筐码" />
            <el-table-column prop="warehouse" label="仓库码" width="120" />
            <el-table-column prop="location" label="储位码" width="100" />
            <el-table-column prop="qty" label="重量" />
            <el-table-column label="操作" fixed="right" width="100" align="center">
              <template v-if="!bottomIsshow" #default="scope">
                <el-button
                  v-hasPerm="'sys:stockIn:edit'"
                  type="primary"
                  link
                  size="small"
                  @click.stop="addBottomDialog(scope.row, 'edit')"
                >
                  修改
                </el-button>
                <el-button
                  v-if="rowList.status != '4'"
                  v-hasPerm="'sys:stockIn:del'"
                  type="danger"
                  size="small"
                  link
                  @click.stop="addBottomDialog(scope.row, 'del')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-if="total > 0"
            v-model:total="totalBottom"
            v-model:page="bottomParams.pageNum"
            v-model:limit="bottomParams.pageSize"
            @pagination="handClikBottom({ code: bottomId, parentCode: bottomId })"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 一级新增/修改弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      @close="handleCloseDialog"
    >
      <el-form ref="roleFormRef" :model="dialogFormData" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="来源类型" prop="sourceCategory">
              <el-select
                v-model="dialogFormData.sourceCategory"
                placeholder="请选择来源类型"
                style="width: 100%"
                filterable
                clearable
              >
                <el-option
                  v-for="item in sourceCategoryList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源编号" prop="sourceCode">
              <el-select
                v-model="dialogFormData.sourceCode"
                placeholder="请选择来源编号"
                style="width: 100%"
                filterable
                clearable
                remote
                :remote-method="(e: any) => getsourceCodeName(e, 'add')"
              >
                <el-option
                  v-for="item in sourceCodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="reason">
              <el-select
                v-model="dialogFormData.reason"
                placeholder="请选择类别"
                style="width: 100%"
                filterable
                clearable
              >
                <el-option
                  v-for="item in reasonList"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库日期" prop="issueDate">
              <el-date-picker
                v-model="dialogFormData.issueDate"
                type="date"
                placeholder="请选择日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row />
        <el-row />

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-noSpace
                v-model="dialogFormData.remark"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="入库类别">
              <el-input v-noSpace
                v-model="dialogFormData.reason"
                type="textarea"
                placeholder="请输入入库类别"
              />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button v-debounce="handleSubmitList" type="primary">提 交</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 二级新增 -->
    <!-- ROW新增/修改弹窗 todo:列表表头增加报存按钮，列表row可以直接编辑-->
    <el-dialog
      v-model="rowDialog.visible"
      :title="rowDialog.title"
      width="1000px"
      @close="handleCloseRowDialog"
    >
      <el-form ref="roleFormRef" :model="dialogRowFormData" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productCode">
              <el-select
                v-model="dialogRowFormData.productCode"
                placeholder="请输入产品名称"
                style="width: 100%"
                filterable
                clearable
                @change="unitValueFormat"
              >
                <el-option
                  v-for="item in productList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="`重量（${unitValue?.label || ''}）`" prop="qty">
              <el-input v-noSpace v-model="dialogRowFormData.qty" placeholder="请输入重量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input v-noSpace v-model="dialogRowFormData.unitPrice" placeholder="请输入单价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总金额" prop="amount">
              <el-input v-noSpace v-model="amountFormat" disabled placeholder="请输入总金额" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="仓库号" prop="warehouse">
              <el-select
                v-model="dialogRowFormData.warehouse"
                placeholder="请输入仓库号"
                style="width: 100%"
                filterable
                clearable
                @visible-change="getStoreNum"
              >
                <el-option
                  v-for="item in storeList"
                  :key="item.code"
                  :label="item.code"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="描述" prop="description">
              <el-input
                v-noSpace
                v-model="dialogRowFormData.description"
                placeholder="请输入描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button v-debounce="handleSubmitRow" type="primary">提 交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- bottom新增/修改弹窗 todo:列表表头增加报存按钮，列表row可以直接编辑-->
    <el-dialog
      v-model="bottomDialog.visible"
      :title="bottomDialog.title"
      width="1000px"
      @close="handleCloseBottomDialog"
    >
      <el-form ref="roleFormRef" :model="dialogbottomFormData" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productCode">
              <el-select
                v-model="dialogbottomFormData.productCode"
                placeholder="请输入产品名称"
                style="width: 100%"
                filterable
                clearable
              >
                <el-option
                  v-for="item in productList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="筐码" prop="basket">
              <el-input v-noSpace v-model="dialogbottomFormData.basket" placeholder="请输入筐码" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="重量" prop="qty">
              <el-input v-noSpace v-model="dialogbottomFormData.qty" placeholder="请输入重量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="储位编号" prop="location">
              <el-select
                v-model="dialogbottomFormData.location"
                placeholder="请输入储位编号"
                style="width: 100%"
                filterable
                clearable
                @visible-change="getLocation"
              >
                <el-option
                  v-for="item in locationList"
                  :key="item.code"
                  :label="item.code + '--' + item.category"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row />

        <el-row />
      </el-form>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button v-debounce="handleSubmitBottom" type="primary">提 交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除 -->
    <el-dialog
      v-model="dialogDel.visible"
      :title="dialogDel.title"
      width="500px"
      @close="dialogDel.visible = false"
    >
      <p>删除后数据将不可显示，且本条库存数据清空，确认是否继续？</p>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click.stop="handleDel()">确 定</el-button>
          <el-button @click.stop="dialogDel.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除 -->
    <el-dialog
      v-model="dialogRowDel.visible"
      :title="dialogRowDel.title"
      width="500px"
      @close="dialogRowDel.visible = false"
    >
      <p>删除后数据将不可显示，且本条库存数据清空，确认是否继续？</p>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click.stop="handleRowDel()">确 定</el-button>
          <el-button @click.stop="dialogRowDel.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除 -->
    <el-dialog
      v-model="dialogBottomDel.visible"
      :title="dialogBottomDel.title"
      width="500px"
      @close="dialogBottomDel.visible = false"
    >
      <p>删除后数据将不可显示，且本条库存数据清空，确认是否继续？</p>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click.stop="handleBottomDel()">确 定</el-button>
          <el-button @click.stop="dialogBottomDel.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核 -->
    <el-dialog
      v-model="dialogApp.visible"
      :title="dialogApp.title"
      width="500px"
      @close="handleCloseDialogApp"
    >
      <el-input v-noSpace v-model="approvedRemake" type="textarea" placeholder="请输入审核意见" />

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click.stop="handlePass('pass')">通 过</el-button>
          <el-button type="primary" @click.stop="handlePass('noPass')">拒绝</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import stockInApi, {
  wareArchivesPageQuery,
  wareArchivesPageVO,
} from "@/api/warehouseManage/stockIn";
import inventoryApi from "@/api/warehouseManage/inventory";
import planOrderApi from "@/api/planManage/planOrderManage";
import movingWorkAPI from "@/api/warehouseManage/movingWork";
import PurchasApi from "@/api/order/purchas";
import SalesAPI from "@/api/order/sales";
import productBomAPI from "@/api/productBom/productBom";
import { tableRowFormatter } from "@/utils/index";
import configApi, { ConfigType } from "@/api/config/config";

const reasonList = ref<{ label: string; value: string }[]>();

const sourceCategoryList = ref([
  { label: "移库单产生", value: 1 },
  { label: "产线生产", value: 2 },
  { label: "盘库产生", value: 3 },
  { label: "采购单", value: 4 },
  { label: "销售订单", value: 5 },
  { label: "退货订单", value: 6 },
  { label: "领料单", value: 7 },
]);
const amountFormat = computed(() => {
  let num = Number(dialogRowFormData.qty) * Number(dialogRowFormData.unitPrice);
  num = isNaN(num) ? 0 : num;
  dialogRowFormData.amount = num.toString();
  return num.toFixed(2);
});

const sourceCategoryValue = (val: number) => {
  let data = sourceCategoryList.value.find((item) => item.value == val)?.label;
  console.log(data);
  return sourceCategoryList.value.find((item) => item.value == val)?.label;
};
const statusValueList = ref([
  { label: "待确认", value: 0 },
  { label: "待审核", value: 1 },
  { label: "已审核待入库", value: 2 },
  { label: "审核拒绝", value: 3 },
  { label: "已入库", value: 4 },
  { label: "入库完成", value: 5 },
]);
const statusValueFormat = (status: number) => {
  return statusValueList.value.find((item) => item.value == status)?.label;
};

const sourceCodeList = ref<
  {
    label: string;
    value: string;
  }[]
>([]);

const storeList = ref<
  {
    name: string;
    code: string;
  }[]
>([]);

const locationList = ref<
  {
    name: string;
    code: string;
    category: string;
  }[]
>([]);

//暂存 按钮isShow
const buttonIsishow = ref(false);

const rowIsshow = ref(true);
const bottomIsshow = ref(true);
//暂存 按钮类型判断新增还是修改
const savebutIsType = ref("");
// 审核意见
const approvedRemake = ref("");
// 新增弹窗
const dialog = reactive({
  title: "",
  visible: false,
  type: "",
});
const departments = ref<Array<{ label: string; value: string }>>([]);
const currencies = ref<Array<{ label: string; value: string }>>([]);

// 新增弹窗
const rowDialog = reactive({
  title: "",
  visible: false,
  type: "",
});

// 新增弹窗
const bottomDialog = reactive({
  title: "",
  visible: false,
  type: "",
});

//// 审核弹窗
const dialogApp = reactive({
  title: "",
  visible: false,
  type: "",
});

// 新增弹窗
const dialogPro = reactive({
  title: "",
  visible: false,
});

//// 删除弹窗
const dialogDel = reactive({
  title: "",
  visible: false,
});

//// 删除弹窗
const dialogRowDel = reactive({
  title: "",
  visible: false,
});

//// 删除弹窗
const dialogBottomDel = reactive({
  title: "",
  visible: false,
});

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);

const queryParams = reactive<wareArchivesPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const rowParams = reactive({
  parentCode: "", // 仓库编号
  pageNum: 1,
  pageSize: 10,
});

const bottomParams = reactive({
  parentCode: "", // 仓库编号
  pageNum: 1,
  pageSize: 10,
});

const rowId = ref("");
const bottomId = ref("");

const pageData = ref<wareArchivesPageVO[]>();

const rowData = ref<TableRow[]>();
const bottomData = ref<BottomDataRow[]>();
interface BottomDataRow {
  code: string; // 编号
  parentCode: string; // 父编号
  rowSeq: number; // 行序号
  docType: string; // 单据类别
  docNo: string; // 单据编号
  productCode: string; // 产品编号
  warehouse: string; // 仓库号
  batch: string; // 批次号
  location: string; // 储位
  basket: string; // 筐號
}
interface TableRow {
  code: string;
  rowSeq: number;
  sortSeq: number;
  sourceCode: string;
  productCode: string;
  description: string;
  warehouse: string;
  batch: string;
  qty: number;
  unit: string;
  unitPrice: number;
  amount: number;
}

interface rowWareArchivesVO {
  /** 储位编号 */
  code?: string;
  /** 仓库编号 */
  warehouse?: string;
  productCode?: string;
  /** 储位容量 */
  // otherName?: string;
  /** 储位的品类 */
  // customer?: string;
  /** 货物品类 */
  // addressName?: string;
}

const total = ref(0);
const totalRow = ref(0);
const totalBottom = ref(0);
const loading = ref(false);
interface DialogFormData {
  id?: number | undefined;
  code: string;
  prefix: string;
  genNo: string;
  issueDate: string;
  department: string;
  reason: string;
  currency: string;
  docType: string;
  sourceCode: string;
  sourceCategory?: number;
  rate: number;
  remark: string;
  status: "0" | "1" | "2" | "3" | "4" | "";
  parentCode: string;
  iocode: string;
}
// 新增/修改form
const dialogFormData = reactive<DialogFormData>({
  id: undefined,
  code: "", // 仓库编号
  prefix: "", // 字首
  genNo: "", // 流水号
  sourceCode: "", //来源编号
  sourceCategory: undefined, //来源类型
  issueDate: "", // 入库日期
  department: "", // 部门
  reason: "", // 入库类别
  currency: "", // 币别
  docType: "", //单据类别
  rate: 0, // 汇率
  remark: "", //备注
  status: "", // 状态（'0'：张签收 或 '1'：李签收 或 '2'：王签收）
  parentCode: "",
  iocode: "",
});
//row信息
const rowObj = ref({
  warehouse: "",
});
// rowList
const rowList = reactive({
  id: 0,
  code: "", // 仓库编号
  prefix: "", // 字首
  genNo: "", // 流水号
  issueDate: "", // 入库日期
  department: "", // 部门

  reason: "", // 入库类别
  currency: "", // 币别
  docType: "", //单据类别
  rate: 0, // 汇率
  remark: "", //备注
  status: "", // 状态（'0'：张签收 或 '1'：李签收 或 '2'：王签收）
});
interface DialogBottomFormData {
  id?: number; // 将 id 定义为可选属性
  code: string; // 编号
  parentCode: string; // 父编号
  rowSeq: string; //  行序号
  docType: string; // 来源编号
  docNo: string; // 单据编号
  productCode: string; // 产品编号
  warehouse: string; //仓库号
  location: string; // 储位
  basket: string; //筐號
  batch: string; //批次号
  iocode: string;
  sourceCategory?: number; //来源类型
  qty?: number; //重量
  // posted: string; //出入仓
}
// 新增/修改form
const dialogbottomFormData = reactive<DialogBottomFormData>({
  id: 0,
  code: "", // 编号
  parentCode: "", // 父编号
  rowSeq: "", // 行序号
  docType: "", // 单据类别
  docNo: "", // 单据编号
  productCode: "", // 产品编号
  location: "", // 储位
  basket: "", //筐號
  warehouse: "", //仓库号
  batch: "", //批次号
  // posted: "", //出入仓
  iocode: "",
  qty: undefined, //重量
  sourceCategory: undefined, //来源类型
});
const bottomObj = ref<DialogBottomFormData | null>(null);
interface DialogRowFormData {
  id?: number; // 将 id 定义为可选属性
  code: string; // 编号
  rowSeq: string; // 序号
  sortSeq: string; // 排序
  productCodeName: string; //产品名称
  sourceCode: string; // 来源编号
  productCode: string; // 产品编号
  description: string; // 描述
  warehouse: string; //仓库号
  batch: string; //批次号
  qty: string; //数量
  unit: string; //单位
  unitPrice: string; //单价
  amount: string; //金额
  parentCode: string;
  iocode: string;
  sourceCategory?: number; //来源类型
}
const dialogRowFormData = reactive<DialogRowFormData>({
  id: undefined, // 将 id 定义为可选属性
  code: "", // 编号
  rowSeq: "", // 序号
  sortSeq: "", // 排序
  sourceCode: "", // 来源编号
  productCode: "", // 产品编号
  productCodeName: "", //产品名称
  description: "", // 描述
  warehouse: "", //仓库号
  batch: "", //批次号
  qty: "", //数量
  unit: "", //单位
  unitPrice: "", //单价
  amount: "", //金额
  parentCode: "",
  iocode: "",
  sourceCategory: undefined, //来源类型
});

const rules = reactive({
  sourceCategory: [{ required: true, message: "来源类型不能为空", trigger: "blur" }],
  sourceCode: [{ required: true, message: "来源编号不能为空", trigger: "blur" }],
  issueDate: [{ required: true, message: "入库日期不能为空", trigger: "blur" }],
  productCode: [{ required: true, message: "产品名称不能为空", trigger: "blur" }],
  qty: [{ required: true, message: "重量不能为空", trigger: "blur" }],
  warehouse: [{ required: true, message: "仓库号不能为空", trigger: "blur" }],
  basket: [{ required: true, message: "筐码不能为空", trigger: "blur" }],
  location: [{ required: true, message: "储位编号不能为空", trigger: "blur" }],
  reason: [{ required: true, message: "入库类别不能为空", trigger: "blur" }],

  // roleIds: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  // email: [
  //   {
  //     pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
  //     message: "请输入正确的邮箱地址",
  //     trigger: "blur",
  //   },
  // ],
  // mobile: [
  //   {
  //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
  //     message: "请输入正确的手机号码",
  //     trigger: "blur",
  //   },
  // ],
});

// 查询
function handleQuery() {
  loading.value = true;
  stockInApi
    .getPage(queryParams)
    .then((data) => {
      pageData.value = [...(data?.list as any)];
      console.log("data", data);
      total.value = data.total;
    })
    .catch((error) => {
      console.log(error, "error");
      //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {
      loading.value = false;
    });
}

// //单位
// const getUnitType = () => {
//   configApi.getConfigListByType("unit" as ConfigType).then((res) => {
//     unitOptions.value = res.map((item: any) => {
//       return {
//         value: item.codeValue,
//         label: item.codeName,
//       };
//     });
//   });
// };

function getConfig(type: string) {
  stockInApi
    .getConfigOption(type)
    .then((data) => {
      if (type == "department") {
        departments.value = data.map((item: any) => {
          return { label: item.codeName, value: item.codeValue };
        });
      } else if (type == "currency") {
        currencies.value = data.map((item: any) => {
          return { label: item.codeName, value: item.codeValue };
        });
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

function handClikRow(row: any) {
  console.log(row);
  loading.value = true;
  rowParams.parentCode = row.code ? row.code : row.parentCode;
  rowId.value = row.code;

  Object.assign(rowList, { ...row });
  if (rowList.status == "4" || rowList.status == "5") {
    rowIsshow.value = true;
    bottomIsshow.value = true;
  } else {
    rowIsshow.value = false;
  }
  stockInApi
    .getRowPage(rowParams)
    .then((data) => {
      rowData.value = [...(data?.list as any)];
      totalRow.value = data.total;
      bottomId.value = "";
      bottomData.value = [];
    })
    .finally(() => {
      loading.value = false;
    });
}

function handClikBottom(row: any) {
  loading.value = true;
  bottomParams.parentCode = row.code ? row.code : row.parentCode;
  bottomId.value = row.code;
  bottomObj.value = { ...row };
  if (rowList.status == "4" || rowList.status == "5") {
    bottomIsshow.value = true;
  } else {
    bottomIsshow.value = false;
  }
  stockInApi
    .getBottomPage(bottomParams)
    .then((data) => {
      bottomData.value = [...(data?.list as any)];
      totalBottom.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  console.log(queryFormRef);
  queryParams.pageNum = 1;
  // queryParams.deptId = undefined;
  // queryParams.createTime = undefined;
  handleQuery();
}

// 新增/修改
function handleOpenDialog(row: wareArchivesPageVO | null = null, type: string) {
  console.log(row);
  let upData = {};
  if (type == "del") {
    dialogDel.title = "删除确认";
    dialogDel.visible = true;
    Object.assign(rowList, { ...row });
  } else if (type == "add") {
    dialog.visible = true;
    dialog.type = "add";
    clearFormData();
  } else if (type == "app") {
    dialogApp.visible = true;
    dialogApp.type = "app";
    dialogApp.title = "审核意见";
    approvedRemake.value = row?.approvalRemark || "";
    Object.assign(rowList, { ...row });
  } else if (type == "appAgin") {
    dialogApp.type = "appAgin";
    approvedRemake.value = row?.approvalRemark || "";
    Object.assign(rowList, { ...row });
    handlePass("pass");
  } else {
    dialog.type = "edit";
    dialog.visible = true;
    upData = { ...row };
    Object.assign(dialogFormData, upData);
    dialog.title = "修改";
    buttonIsishow.value = true;
    savebutIsType.value = "edit"; //暂存类型判断
  }
}

function clearFormData() {
  let data = {
    code: "", // 仓库编号
    prefix: "", // 字首
    genNo: "", // 流水号
    issueDate: "", // 入库日期
    department: "", // 部门
    sourceCode: "", //来源编号
    sourceCategory: "", //来源类型

    reason: "", // 入库类别
    currency: "", // 币别
    rate: 0, // 汇率
    remark: "", //备注
    status: "", // 状态（'0'：张签收 或 '1'：李签收 或 '2'：王签收）
  };
  Object.assign(dialogFormData, data);
}

function clearRowFormData() {
  let data = {
    code: "", // 编号
    rowSeq: "", // 序号
    sortSeq: "", // 排序
    sourceCode: "", // 来源编号
    productCode: "", // 产品编号
    description: "", // 描述
    warehouse: "", //仓库号
    batch: "", //批次号
    qty: "", //数量
    unit: "", //单位
    unitPrice: "", //单价
    amount: "", //金额
  };
  Object.assign(dialogRowFormData, data);
}

function clearBottomFormData() {
  let data = {
    code: "", // 编号
    parentCode: "", // 父编号
    rowSeq: "", // 行序号
    docType: "", // 单据类别
    docNo: "", // 单据编号
    productCode: "", // 产品编号
    location: "", // 储位
    basket: "", //筐號
    warehouse: "", //仓库号
    batch: "", //批次号
    qty: undefined, //重量
    // posted: "", //出入仓
  };
  Object.assign(dialogbottomFormData, data);
}

// 新增/修改
function addRowDialog(row: rowWareArchivesVO | null = null, type: string) {
  let upData = {};
  if (type == "add") {
    rowDialog.visible = true;
    rowDialog.type = "add";
    clearRowFormData();
  } else if (type == "edit") {
    rowDialog.visible = true;
    rowDialog.type = "edit";
    unitValueFormat(row?.productCode);
    upData = { ...row };
    Object.assign(dialogRowFormData, upData);
  } else {
    rowDialog.type = "del";
    dialogRowDel.visible = true;
    upData = { ...row };
    Object.assign(dialogRowFormData, upData);
  }
}

function addBottomDialog(row: rowWareArchivesVO | null = null, type: string) {
  let upData = {};
  if (type == "add") {
    bottomDialog.type = "add";
    bottomDialog.visible = true;
    clearBottomFormData();
  } else if (type == "edit") {
    bottomDialog.visible = true;
    bottomDialog.type = "edit";
    upData = { ...row };
    Object.assign(dialogbottomFormData, upData);
  } else {
    console.log(111);
    bottomDialog.type = "del";
    dialogBottomDel.visible = true;
    upData = { ...row };
    Object.assign(dialogbottomFormData, upData);
  }
}

// 确认删除
function handleDel() {
  stockInApi
    .delCk({ id: rowList.id })
    .then(() => {
      ElMessage({
        // 提交成功的处理逻辑提取到此处
        type: "success",
        message: "删除成功",
      });
      dialogDel.visible = false;
      handleQuery();
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    });
}

//删除
function handleRowDel() {
  stockInApi
    .delRow({ id: dialogRowFormData.id })
    .then(() => {
      ElMessage({
        // 提交成功的处理逻辑提取到此处
        type: "success",
        message: "删除成功",
      });
      dialogRowDel.visible = false;
      handClikRow({ parentCode: rowId.value, code: rowId.value });
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    });
}

function handleBottomDel() {
  stockInApi
    .delBottom({ id: dialogbottomFormData?.id })
    .then(() => {
      ElMessage({
        // 提交成功的处理逻辑提取到此处
        type: "success",
        message: "删除成功",
      });
      dialogBottomDel.visible = false;
      handClikBottom({ parentCode: bottomId.value, code: bottomId.value });
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
}

// 关闭弹窗===清除选中产品单位值
function handleCloseRowDialog() {
  rowDialog.visible = false;
  unitValue.value = {};
}
// 选中产品单位值
const unitValue = ref<{ label?: string; value?: string }>({});
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
// 产品列表
const productList = ref<
  {
    label: string;
    value: string;
    unit: string;
    price: string;
  }[]
>([]);
// 二级选择产品名称带出unit记录单位
const unitValueFormat = (value: any) => {
  let unit = productList.value.find((item) => item.value === value)?.unit;
  unitValue.value = unitOptions.value.find((item) => item.value === unit) as any;
  dialogRowFormData.unitPrice = productList.value.find((item) => item.value === value)
    ?.price as any;
};
const unitFormat = (unit: any) => {
  if (!unit) return;
  let unitLabel = unitOptions.value.find((item) => item.value === unit.toLowerCase())?.label;
  return unitLabel;
};
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};

// 获取产品列表
const getProductName = () => {
  configApi.getProductList({ pageNum: 1, pageSize: 999 }).then((data) => {
    productList.value = data?.list.map((item: any) => {
      return { label: item.productName, value: item.code, unit: item.unit, price: item.price };
    });
  });
};

function handleCloseBottomDialog() {
  bottomDialog.visible = false;
}

function handleClosedialogDel() {
  dialogDel.visible = false;
}

function handleCloseDialogApp() {
  dialogApp.visible = false;
}
const roleFormRef = ref(ElForm);
// 提交row
function handleSubmitList() {
  roleFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    const apiCall = dialog.type === "add" ? stockInApi.addTopStore : stockInApi.addTopStore;
    // if (dialog.type == "add") {
    //   dialogFormData.status = "0"; //默认待审核
    // }
    dialogFormData.iocode = "i"; // 默认出库
    if (dialog.type == "add") {
      delete dialogFormData.id;
    }
    apiCall(dialogFormData)
      .then(() => {
        ElMessage({
          type: "success",
          message: "操作成功",
        });
        handleQuery();
        rowId.value = ""; //清空单击选中id
        dialog.visible = false;
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      });
  });
}

function handleSubmitRow() {
  roleFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    const apiCall =
      rowDialog.type === "add" ? stockInApi.addCenterStore : stockInApi.addCenterStore;
    dialogRowFormData.parentCode = rowId.value;
    dialogRowFormData.iocode = "i"; // 默认出库
    dialogRowFormData.unit = unitValue.value?.value as any;

    if (rowDialog.type == "add") {
      delete dialogRowFormData.id;
    }
    apiCall(dialogRowFormData)
      .then(() => {
        ElMessage({
          type: "success",
          message: "操作成功",
        });
        handClikRow({ parentCode: rowId.value, code: rowId.value });
        rowDialog.visible = false;
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      });
  });
}

function handleSubmitBottom() {
  roleFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    const apiCall =
      bottomDialog.type === "add" ? stockInApi.addBottomStore : stockInApi.addBottomStore;
    dialogbottomFormData.parentCode = bottomId.value;
    dialogbottomFormData.iocode = "i"; // 默认出库
    if (bottomDialog.type == "add") {
      delete dialogbottomFormData.id;
    }
    dialogbottomFormData.warehouse = bottomObj?.value?.warehouse ?? ""; // 提供默认值
    console.log(dialogbottomFormData);
    apiCall(dialogbottomFormData)
      .then(() => {
        ElMessage({
          type: "success",
          message: "操作成功",
        });
        handClikBottom({ parentCode: bottomId.value, code: bottomId.value });
        bottomDialog.visible = false;
        if (bottomDialog.type == "add") {
          handleQuery();
        }
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      });
  });
}

//是否通过
function handlePass(type: string) {
  const apiCall = stockInApi.appTopStore;
  dialogFormData.remark = approvedRemake.value;
  dialogFormData.id = rowList?.id;
  dialogFormData.code = rowList?.code;
  if (dialogApp.type == "appAgin") {
    type = "appAgin";
    dialogFormData.status = "1"; //待审核
  }

  if (type == "pass") {
    dialogFormData.status = "2"; //通过
    dialogApp.type == "pass";
  } else if (type == "noPass") {
    console.log(111);
    dialogFormData.status = "3"; //不通过
    dialogApp.type == "noPass";
  }

  console.log(dialogFormData.status);
  apiCall(dialogFormData)
    .then(() => {
      ElMessage({
        type: "success",
        message: "操作成功",
      });
      handleQuery();
      dialogApp.visible = false;
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    });
}

// 提交
// function handleSubmitList() {
//   const apiCall = dialog.type === "add" ? stockInApi.addStore : stockInApi.editCk;
//   apiCall(dialogFormData)
//     .then((data) => {
//       if (data) {
//         ElMessage({
//           // 提交成功的处理逻辑提取到此处
//           type: "success",
//           message: "提交成功",
//         });
//         dialog.visible = false;
//         clearFormData();
//         handleQuery();
//       } else {
//         // 提供更具体的错误信息（如果可能的话，根据API返回的具体错误信息进行展示）
//         ElMessage({
//           type: "error",
//           message: "提交失败", // 更具体的错误信息
//         });
//       }
//     })
//     .catch((error) => {
//       // 添加catch以处理API调用过程中可能出现的异常
//       console.error(error); // 在控制台输出错误信息，便于调试
//       ElMessage({
//         type: "error",
//         message: "发生未知错误，请稍后再试。", // 告知用户发生了未知错误
//       });
//     });
// }
const productCodeFormat = (productCode: string) => {
  let data = productList.value.find((item) => item.value == productCode);
  console.log(data);
  if (!data) {
    return "-";
  }
  return data?.label + "/" + data?.value;
};
const getsourceCodeName = (query: string, type: string) => {
  // console.log(query);
  // console.log(dialogFormData.sourceCategory);

  // console.log(queryParams);
  // let data = {
  //   pageNum: 1,
  //   pageSize: 1,
  // };
  let status = type == "add" ? dialogFormData.sourceCategory : queryParams.sourceCategory;
  console.log(status);

  if (status == 1) {
    let data = {
      pageNum: 1,
      pageSize: 999,
      code: query,
      status: 0,
    };

    inventoryApi
      .getPage(data)
      .then((data: any) => {
        let list = data?.list.map((item: any) => {
          return {
            label: item.code,
            value: item.code,
          };
        });
        sourceCodeList.value = [...(list as any)];
      })
      .finally(() => {
        // loading.value = false;
      });
  } else if (status == 2) {
    let data = {
      pageNum: 1,
      pageSize: 999,
      code: query,
      statusList: [5, 6],
    };
    planOrderApi
      .getPage(data)
      .then((data: any) => {
        let list = data?.list.map((item: any) => {
          return {
            label: item.code,
            value: item.code,
          };
        });
        sourceCodeList.value = [...(list as any)];
      })
      .catch((err) => {
        console.log(err);
        // ElMessage.error(`${err}`);
        // handleCloseDialog();
        // handleResetQuery();
      })
      .finally(() => {
        // loading.value = false;
      });
  } else if (status == 3) {
    let data = {
      pageNum: 1,
      pageSize: 999,
      code: query,
      statusList: [1, 2],
    };
    movingWorkAPI
      .getPage(data)
      .then((data) => {
        let list = data?.list.map((item: any) => {
          return {
            label: item.code,
            value: item.code,
          };
        });
        sourceCodeList.value = [...(list as any)];
      })
      .finally(() => {
        loading.value = false;
      });
  } else if (status == 4) {
    // {"pageNum":1,"pageSize":10,"statusList":[2],"code":"2","status":2}
    let data = {
      pageNum: 1,
      pageSize: 999,
      code: query,
      // status: "2",
      statusList: [2, 4, 5],
    };
    PurchasApi.getPage(data)
      .then((data: any) => {
        let list = data?.list.map((item: any) => {
          return {
            label: item.code,
            value: item.code,
          };
        });
        sourceCodeList.value = [...(list as any)];
      })
      .catch((err) => {
        console.log(err);
        // ElMessage.error(`${err}`);
        // handleCloseDialog();
        // handleResetQuery();
      })
      .finally(() => {
        loading.value = false;
      });
  } else if (status == 5 || status == 6) {
    // {"isReturnOrder":0,"pageNum":1,"pageSize":10,"status":"3","code":"1"}
    let data = {
      pageNum: 1,
      pageSize: 999,
      code: query,
      status: "3",
      isReturnOrder: 0,
    };
    if (status == 6) {
      data.isReturnOrder = 1;
    }

    SalesAPI.getPage(data)
      .then((data) => {
        let list = data?.list.map((item: any) => {
          return {
            label: item.code,
            value: item.code,
          };
        });
        sourceCodeList.value = [...(list as any)];
      })
      .catch((error) => {
        //ElMessage.error(`${error}`); //注释报错弹窗
      })
      .finally(() => {
        loading.value = false;
      });
  }

  // if (query) {
  //   loading.value = true
  //   setTimeout(() => {
  //     loading.value = false
  //     options.value = list.value.filter((item) => {
  //       return item.label.toLowerCase().includes(query.toLowerCase())
  //     })
  //   }, 200)
  // } else {
  //   options.value = []
  // }
};

//查询仓库号

const getStoreNum = () => {
  stockInApi.getStoreNum({ pageNum: 0, pageSize: 30 }).then((res) => {
    storeList.value = res?.list;
  });
};

const getLocation = () => {
  stockInApi.getLocationList({ warehouse: bottomObj?.value?.warehouse, code: "" }).then((res) => {
    locationList.value = res;
  });
};

//获取入库类型配置项
const getInStockConfig = () => {
  configApi.getConfigListByType(ConfigType.TRAN_IN_REASON).then((res: any) => {
    reasonList.value = res.map((ele: any) => {
      return {
        value: ele.codeValue.toString(),
        label: ele.codeName,
      };
    });
  });
};
onMounted(() => {
  getInStockConfig();
  getProductName();
  handleQuery();
  getConfig("department");
  getConfig("currency");
  getUnitList();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;

.el-table :deep(.cell) {
  // padding: 0 !important;
}

.el-table :deep(.el-table__cell) {
  // padding: 0 !important;
  text-align: center;
}

.el-form :deep(.el-form-item) {
  min-width: 220px;
}
</style>
